<template>
  <BasicModal
    v-bind="$attrs"
    :title="t('routes.demo.FigureDocSettings.extract')"
    @register="register"
    @ok="handleSubmit"
    @cancel="handleCancel"
    :destroyOnClose="true"
    :minHeight="450"
    :width="1400"
  >
    <Row :gutter="12">
      <Col span="12">
        <h2>{{ t('routes.demo.FigureDocSettings.TitleExtract') }}</h2>
        <Table
          :columns="titleColumns"
          :data-source="titleDictionaryList"
          bordered
          row-key="userName"
        >
          <template
            v-for="col in ['docSystemName', 'partSystemName']"
            #[col]="{ text, record }"
            :key="col"
          >
            <div>
              <Select
                v-if="editableData[record.userName] && col === 'docSystemName'"
                v-model:value="editableData[record.userName][col]"
                style="width: 100%"
              >
                <SelectOption
                  v-for="(item, index) in docSysList"
                  :key="index"
                  :value="item.label"
                  >{{ item.value }}</SelectOption
                >
              </Select>
              <Select
                v-else-if="editableData[record.userName] && col === 'partSystemName'"
                v-model:value="editableData[record.userName][col]"
                style="width: 100%"
              >
                <SelectOption
                  v-for="(item, index) in partSysList"
                  :key="index"
                  :value="item.label"
                  >{{ item.value }}</SelectOption
                >
              </Select>
              <template v-else>{{ getTitle(col, text) }}</template>
            </div>
          </template>
          <template #operation="{ record }">
            <div class="editable-row-operations">
              <span v-if="editableData[record.userName]">
                <a @click="save(record.userName)">{{ t('common.saveText') }}</a>
                <Popconfirm
                  :title="t('common.confirmCancelText')"
                  @confirm="cancel(record.userName)"
                >
                  <a>{{ t('common.cancelText') }}</a>
                </Popconfirm>
              </span>
              <span v-else>
                <a @click="edit(record.userName)">{{ t('common.edit') }}</a>
              </span>
            </div>
          </template>
        </Table>
      </Col>
      <Col span="12">
        <h2>{{ t('routes.demo.FigureDocSettings.detail') }}</h2>
        <Table
          :columns="detailColumns"
          :data-source="detailDictionaryList"
          bordered
          row-key="userName"
        >
          <template v-for="col in ['systemName']" #[col]="{ text, record }" :key="col">
            <div>
              <Select
                v-if="detailEditableData[record.userName]"
                v-model:value="detailEditableData[record.userName][col]"
                style="width: 100%"
              >
                <SelectOption v-for="(item, index) in sysList" :key="index" :value="item.label">{{
                  item.value
                }}</SelectOption>
              </Select>
              <template v-else>{{ getTitle(col, text) }}</template>
            </div>
          </template>
          <template #operation="{ record }">
            <div class="editable-row-operations">
              <span v-if="detailEditableData[record.userName]">
                <a @click="detailSave(record.userName)">{{ t('common.saveText') }}</a>
                <Popconfirm
                  :title="t('common.confirmCancelText')"
                  @confirm="detailCancel(record.userName)"
                >
                  <a>{{ t('common.cancelText') }}</a>
                </Popconfirm>
              </span>
              <span v-else>
                <a @click="detailEdit(record.userName)">{{ t('common.edit') }}</a>
              </span>
            </div>
          </template>
        </Table>
      </Col>
    </Row>
    <Row :gutter="12" style="margin-top: 12px">
      <Col span="12" />
      <Col span="12" style="display: flex">
        <Upload :customRequest="customUpload" :beforeUpload="beforeUpload">
          <a-button type="dashed">{{ t('routes.demo.FigureDocSettings.SelectTemplate') }}</a-button>
        </Upload>
        <Divider type="vertical" />
        <a-button type="dashed" @click="downloadTemplate">{{
          t('routes.demo.FigureDocSettings.DownloadTemplate')
        }}</a-button>
        <Divider type="vertical" />
        <a-button type="dashed" @click="deleteTemplate">{{
          t('routes.demo.FigureDocSettings.DeleteTemplate')
        }}</a-button>
      </Col>
    </Row>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { cloneDeep } from 'lodash-es';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Row, Col, Divider, Upload } from 'ant-design-vue';
  import {
    getDocTypeDataList,
    getDocTypeDataListSystem,
    updateDocTypeDataList,
    deleteDocTypeDataList,
    downloadDocTypeDataList,
    AddDocTypeTemplate,
  } from '/@/api/demo/system';
  import { Select, SelectOption, Popconfirm, Table } from 'ant-design-vue';

  const { t } = useI18n();
  const { createMessage } = useMessage();
  const DocTypeId = ref('');
  const docSysList = ref([]);
  const partSysList = ref([]);
  const sysList = ref([]);
  const titleDictionaryList = ref([]);
  const detailDictionaryList = ref([]);
  const editableData = ref({});
  const detailEditableData = ref({});
  const titleColumns = ref([
    {
      title: t('routes.demo.FigureDocSettings.userName'),
      dataIndex: 'userName',
      width: 100,
    },
    {
      title: t('routes.demo.FigureDocSettings.systemNameFigure'),
      dataIndex: 'docSystemName',
      width: 150,
      slots: { customRender: 'docSystemName' },
    },
    {
      title: t('routes.demo.FigureDocSettings.systemNamePart'),
      dataIndex: 'partSystemName',
      width: 150,
      slots: { customRender: 'partSystemName' },
    },
    {
      title: t('common.action'),
      dataIndex: 'operation',
      width: 100,
      slots: { customRender: 'operation' },
    },
  ]);
  const detailColumns = ref([
    {
      title: t('routes.demo.FigureDocSettings.userName'),
      dataIndex: 'userName',
      width: 100,
      fixed: 'left',
    },
    {
      title: t('routes.demo.FigureDocSettings.systemName'),
      dataIndex: 'systemName',
      width: 150,
      slots: { customRender: 'systemName' },
    },
    {
      title: t('common.action'),
      dataIndex: 'operation',
      width: 120,
      slots: { customRender: 'operation' },
    },
  ]);
  const upLoadModUrl = ref('');
  const upLoadFileName = ref('');

  // 计算命名
  const getTitle = (col, text) => {
    if (col === 'docSystemName') {
      if (text !== '') {
        return docSysList.value.find((item) => item.label === text).value;
      } else {
        return text;
      }
    } else if (col === 'partSystemName') {
      if (text !== '') {
        return partSysList.value.find((item) => item.label === text).value;
      } else {
        return text;
      }
    } else if (col === 'systemName') {
      if (text !== '') {
        return sysList.value.find((item) => item.label === text).value;
      } else {
        return text;
      }
    }
  };

  const edit = (key: string) => {
    editableData.value[key] = cloneDeep(
      titleDictionaryList.value.filter((item) => key === item.userName)[0],
    );
  };
  const save = (key: string) => {
    Object.assign(
      titleDictionaryList.value.filter((item) => key === item.userName)[0],
      editableData.value[key],
    );
    delete editableData.value[key];
  };
  const cancel = (key: string) => {
    delete editableData.value[key];
  };

  const detailEdit = (key: string) => {
    detailEditableData.value[key] = cloneDeep(
      detailDictionaryList.value.filter((item) => key === item.userName)[0],
    );
  };
  const detailSave = (key: string) => {
    Object.assign(
      detailDictionaryList.value.filter((item) => key === item.userName)[0],
      detailEditableData.value[key],
    );
    delete detailEditableData.value[key];
  };
  const detailCancel = (key: string) => {
    delete detailEditableData.value[key];
  };

  // 提交
  const handleSubmit = async () => {
    for (let item of titleDictionaryList.value) {
      if (
        (item.userName === '图纸编号' || item.userName === '图纸名称') &&
        (item.docSystemName === '' || item.partSystemName === '')
      ) {
        createMessage.error(t('routes.demo.FigureDocSettings.noEmpty'));
        return;
      }
    }
    for (let item of detailDictionaryList.value) {
      if ((item.userName === '代号' || item.userName === '名称') && item.systemName === '') {
        createMessage.error(t('routes.demo.FigureDocSettings.noEmpty1'));
        return;
      }
    }
    const params = {
      titleDictionaryList: titleDictionaryList.value,
      detailDictionaryList: detailDictionaryList.value,
      upLoadModUrl: upLoadModUrl.value,
      upLoadFileName: upLoadFileName.value,
    };
    const res = await updateDocTypeDataList(DocTypeId.value, params);
    if (res) {
      createMessage.success(t('common.saveSuccess'));
      handleCancel();
    }
  };
  // 取消
  const handleCancel = () => {
    DocTypeId.value = '';
    editableData.value = {};
    detailEditableData.value = {};
    upLoadModUrl.value = '';
    upLoadFileName.value = '';
    closeModal();
  };

  // 下载模板
  const downloadTemplate = () => {
    downloadDocTypeDataList(DocTypeId.value).then((res) => {
      if (res) {
        createMessage.success(t('common.downLoadSuccess'));
      }
    });
  };

  // 删除模板
  const deleteTemplate = () => {
    deleteDocTypeDataList(DocTypeId.value).then((res) => {
      if (res) {
        createMessage.success(t('common.delSuccessText'));
        reloadData();
      }
    });
  };

  const reloadData = () => {
    getDocTypeDataList(DocTypeId.value).then((res) => {
      titleDictionaryList.value = res.titleDictionaryList;
      detailDictionaryList.value = res.detailDictionaryList;
      upLoadModUrl.value = res.upLoadModUrl;
      upLoadFileName.value = res.upLoadFileName;
    });
  };

  // 文件上传前
  const beforeUpload = (file: any) => {
    // 只允许上传mod文件类型
    const arr = file.name.split('.');
    const extension = arr[arr.length - 1];
    if (extension !== 'mod') {
      createMessage.error(t('routes.demo.FigureDocSettings.onlyUploadMod'));
      return false;
    }
    return true;
  };

  // 文件上传
  const customUpload = (e: any) => {
    const formData = new FormData();
    formData.append('file', e.file);
    AddDocTypeTemplate(DocTypeId.value, formData).then((res) => {
      titleDictionaryList.value = res.titleDictionaryList;
      detailDictionaryList.value = res.detailDictionaryList;
      upLoadModUrl.value = res.upLoadModUrl;
      upLoadFileName.value = res.upLoadFileName;
      createMessage.success(t('common.uploadSuccess'));
    });
  };

  // 初始化弹窗
  const [register, { setModalProps, closeModal }] = useModalInner((data) => {
    setModalProps({ confirmLoading: false });
    DocTypeId.value = data.id;
    getDocTypeDataListSystem(data.id).then((res) => {
      docSysList.value = res.docSysList;
      partSysList.value = res.partSysList;
      sysList.value = res.sysList;
      reloadData();
    });
  });
</script>

<style lang="less" scoped>
  .editable-row-operations a {
    margin-right: 8px;
  }

  ::v-deep(.ant-upload-list) {
    display: none !important;
  }
</style>
